﻿#include <graphics.h>
#include <iostream>
#include <string>

#include "GameState.h"
#include "GameLogic.h"
#include "GameRenderer.h"

int main() {
    GameState gameState;
    GameLogic gameLogic(gameState);
    GameRenderer gameRenderer(gameState);

    BeginBatchDraw();
    
    // 游戏开始前绘制一次
    gameRenderer.render();

    ExMessage msg{};
    while (gameState.isRunning()) {
        DWORD startTime = GetTickCount();
        // 处理事件
        while (peekmessage(&msg)) {
            // 处理鼠标点击事件
            if (msg.message == WM_LBUTTONDOWN) {
                // 更新游戏状态
                gameLogic.updateGameState(msg.x, msg.y);

                // 重新绘制游戏界面
                gameRenderer.render();

                // 检查游戏是否结束
                int gameResult = gameLogic.checkGameOver(msg.x, msg.y);

                if (gameResult == 1) {
                    // 当前玩家胜利
                    std::wstring winner = std::wstring(1, gameState.getCurrentPiece()) + L" 玩家获胜！游戏重置";
                    MessageBoxW(GetHWnd(), winner.c_str(), L"游戏结束", MB_OK);
                    // 重置游戏
                    gameState.resetGame();
                } else if (gameResult == 2) {
                    // 平局
                    MessageBoxW(GetHWnd(), L"平局！游戏重置", L"游戏结束", MB_OK);
                    // 重置游戏
                    gameState.resetGame();
                }
            }
        }
        DWORD endTime = GetTickCount();
        DWORD deltaTime = endTime - startTime;
        if(deltaTime < 16){
            Sleep(16 - deltaTime);
        }
    }
    
    EndBatchDraw();
    return 0;
}
